import React, { Component } from 'react';
import Pubsub from 'pubsub-js'

export default class Search extends Component {

    search = async() => {
        //获取用户的输入(连续结构赋值)
        const {keyWordElement: {value: keyword}} = this;
        console.log(keyword);
        //发送请求前，通知List更新状态
        Pubsub.publish('atguigu', {isFirst: false, isLoading: true});
        //发送网络请求---使用fetch发送（未优化）
		/* fetch(`/api1/search/users2?q=${keyWord}`).then(
			response => {
				console.log('联系服务器成功了');
				return response.json()
			},
			error => {
				console.log('联系服务器失败了',error);
				return new Promise(()=>{})
			}
		).then(
			response => {console.log('获取数据成功了',response);},
			error => {console.log('获取数据失败了',error);}
		) */
        //发送网络请求---使用fetch发送（优化）
        try {
            const response = await fetch('/api1/search/users2?q=' + keyword);
            const data = await response.json();
            console.log(data);
            Pubsub.publish('atguigu', {isLoading: false, users: data.items});
        } catch (error) {
            console.log('请求出错', error);
            Pubsub.publish('atguigu', {isLoading: false, err: error.message});
        }
    }

    render() {
        return (
            <section className="jumbotron">
                <h3 className="jumbotron-heading">搜索Github用户</h3>
                <div>
                    <input type="text" ref={c => this.keyWordElement = c} placeholder="输入内容进行搜索"/>&nbsp;
                    <button onClick={this.search}>搜索</button>
                </div>
            </section>
        )
    }
}
